// 导入必要的React组件和hooks
import React, { useState, useEffect } from "react";
// 导入Ant Design图标组件
import { UndoOutlined, UnorderedListOutlined, AppstoreOutlined, LineHeightOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
// 导入Ant Design UI组件
import { Button, Table, Modal, Radio, Pagination, message } from 'antd';
// 导入路由导航hook
import { useNavigate } from 'react-router-dom';
// 导入axios用于发送HTTP请求
import axios from 'axios';
// 导入样式模块
import style from '../../cssmodule/PFLCSS.module.css'
import * as XLSX from 'xlsx';

// 项目函件列表组件
const ProjectFunctionList = () => {
    // 初始化路由导航hook
    const navigate = useNavigate();
    // 控制模态框显示状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 存储选中的确认类型值
    const [selectedValue, setSelectedValue] = useState(null);
    // 存储表格数据
    const [tableData, setTableData] = useState([]);
    // 存储选中的任务阶段
    const [selectedPhase, setSelectedPhase] = useState('');
    // 存储搜索条件：创建人
    const [searchCreator, setSearchCreator] = useState('');
    // 存储搜索条件：联系电话
    const [searchPhone, setSearchPhone] = useState('');

    // 分页相关状态
    const [currentPage, setCurrentPage] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(10); // 每页显示条数
    const [total, setTotal] = useState(0); // 总数据条数
    const [loading, setLoading] = useState(false); // 加载状态

    // 文件上传相关状态
    const [pdfFile, setPdfFile] = useState(null); // PDF文件
    const [wordFile, setWordFile] = useState(null); // Word文件
    const [uploading, setUploading] = useState(false); // 上传状态
    const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false);
    const [previewData, setPreviewData] = useState(null);
    const [viewMode, setViewMode] = useState('list'); // 'list' 或 'card'

    // 计算天数的函数
    const calculateDays = (startDate, endDate) => {
        const start = new Date(startDate);
        const end = new Date(endDate);
        const diffTime = Math.abs(end - start);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return diffDays;
    };

    // 获取当前日期字符串
    const getCurrentDateString = () => {
        const now = new Date();
        return now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    };
// const [kk,setKK] = useState(false)
//     const islone =()=>{
//         axios.get(`http://localhost:3000/getUsers`).then(res=>{
//             // console.log(res.data.data,235252525);//////////////
//             // if(res.data/)
//         })
//     }
// // islone()

    // 获取列表数据的函数
    const getList = async (page = currentPage, size = pageSize) => {
        setLoading(true); // 设置加载状态
        try {
            // 发送GET请求获取数据
            const response = await axios.get('http://localhost:3000/yjl/pdfList', {
                params: {
                    page,
                    size,
                    creator: searchCreator,
                    phone: searchPhone
                }
            });
            // 如果请求成功，更新表格数据和总数
            if (response.data && response.data.pdflist) {
                // 自动计算并更新天数
                const updatedData = response.data.pdflist.map(item => {
                    if (item.createTime) {
                        const days = calculateDays(item.createTime, new Date());
                        return { ...item, days };
                    }
                    return item;
                });
                
                setTableData(updatedData);
                setTotal(response.data.total || 0);
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            message.error('获取数据失败');
        } finally {
            setLoading(false); // 无论成功失败都关闭加载状态
        }
    };

    // 组件挂载时获取数据
    useEffect(() => {
        getList();
    }, [currentPage, pageSize, searchCreator, searchPhone]);

    // 处理刷新按钮点击
    const handleRefresh = () => {
        clearTimeout();
        message.success('正在刷新数据...');
        getList();
        setTimeout(() => {
            message.success('刷新完成');
        }, 1000)
    };

    // 处理页码改变
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    // 处理每页条数改变
    const handlePageSizeChange = (current, size) => {
        setPageSize(size);
        setCurrentPage(1); // 切换每页条数时重置为第一页
    };

    // 处理搜索按钮点击
    const handleSearch = () => {
        setCurrentPage(1);
        getList(1, pageSize);
    };

    // 显示新增函件模态框
    const showModal = () => {
        setIsModalOpen(true);
    };

    // 处理模态框确认按钮点击
    const handleOk = () => {
        handleAddCorrespondence();
    };

    // 处理模态框取消按钮点击
    const handleCancel = () => {
        setIsModalOpen(false);
        setSelectedValue(null);
        setSelectedPhase('');
        setPdfFile(null);
        setWordFile(null);
    };

    // 处理单选按钮改变
    const onChangeRadio = (e) => {
        setSelectedValue(e.target.value);
    };

    // 文件上传功能
    const uploadFile = async (file, type) => {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', type);

        try {
            // 发送POST请求上传文件
            const response = await axios.post('http://localhost:3000/yjl/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                message.success(`${type === 'pdf' ? 'PDF' : 'Word'}文件上传成功`);
                return response.data.files[0].url;
            } else {
                message.error('文件上传失败');
                return null;
            }
        } catch (error) {
            console.error('文件上传错误:', error);
            message.error('文件上传失败');
            return null;
        }
    };

    // 处理新增函件
    const handleAddCorrespondence = async () => {
        // 验证必填信息
        if (!selectedValue || !selectedPhase || !pdfFile || !wordFile) {
            message.warning('请填写完整信息');
            return;
        }

        setUploading(true);
        try {
            // 上传PDF文件
            const pdfUrl = await uploadFile(pdfFile, 'pdf');
            if (!pdfUrl) {
                setUploading(false);
                return;
            }

            // 上传Word文件
            const wordUrl = await uploadFile(wordFile, 'word');
            if (!wordUrl) {
                setUploading(false);
                return;
            }

            // 获取当前时间
            const currentTime = getCurrentDateString();
            
            // 构建新增函件数据
            const correspondenceData = {
                ID: tableData.length + 1,
                type: selectedValue === '9' ? '阶段确认' : '需求确认',
                phase: selectedPhase,
                signFile: pdfFile.name,
                origFile: wordFile.name,
                client: '李舟', // 可以从表单获取
                phone: '18112345678', // 可以从表单获取
                status: '待签署',
                creator: '李舟', // 可以从登录信息获取
                createTime: currentTime,
                updateTime: currentTime,
                days: 0 // 初始天数为0
            };

            // 发送POST请求新增函件
            const response = await axios.post('http://localhost:3000/yjl/add', correspondenceData);

            if (response.data.success) {
                message.success('新增函件成功');
                setIsModalOpen(false);
                setSelectedValue(null);
                setSelectedPhase('');
                setPdfFile(null);
                setWordFile(null);
                getList();
            } else {
                message.error('新增函件失败');
            }
        } catch (error) {
            console.error('新增函件错误:', error);
            message.error('新增函件失败');
        } finally {
            setUploading(false);
        }
    };

    // 处理删除函件
    const handleDelete = async (id) => {
        try {
            const response = await axios.delete(`http://localhost:3000/yjl/deletePdf/${id}`);
            if (response.data.success) {
                message.success('删除成功');
                getList();
            }
        } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败');
        }
    };

    const handlePreview = (record) => {
        setPreviewData(record);
        setIsPreviewModalOpen(true);
    };

    const handlePreviewCancel = () => {
        setIsPreviewModalOpen(false);
        setPreviewData(null);
    };

    // 切换视图模式
    const handleViewModeChange = (mode) => {
        setViewMode(mode);
    };

    // 处理文件点击
    const handleFileClick = (fileName, type) => {
        const fileUrl = `http://localhost:3000/public/uploads/${fileName}`;
        window.open(fileUrl, '_blank');
    };

    // 导出Excel函数
    const handleExportExcel = () => {
        if (!tableData.length) {
            message.info('没有可导出的数据');
            return;
        }
        const dataToExport = tableData.map(row => ({
            'ID': row.ID,
            '确认类型': row.type,
            '确认阶段': row.phase,
            '签字文件': row.signFile,
            '原文件': row.origFile,
            '客户对接人': row.client,
            '联系电话': row.phone,
            '签署状态': row.status,
            '创建人': row.creator,
            '创建时间': row.createTime,
            '更新时间': row.updateTime,
            '天数': row.days
        }));
        const ws = XLSX.utils.json_to_sheet(dataToExport);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '函件列表');
        XLSX.writeFile(wb, '项目函件列表.xlsx');
    };

    // 渲染组件
    return (
        <>
            <div>
                {/* 项目标题区域 */}
                <div>
                    <p className={style['project-title']}>
                        <span className={style['project-id']}>项目函数</span>
                        <span className={style['project-id']}>项目编号</span>
                        <span className={style['project-id']}>P123123231231</span>
                        <span className={style['project-id']}>项目名称:</span>
                        <span className={style['project-id']}>CRM系统</span>
                    </p>
                </div>

                {/* 主体内容区域 */}
                <div className={style['project-body']}>
                    {/* 顶部操作区域 */}
                    <div className={style['project-body-up']}>
                        <div>
                            {/* 刷新和新增按钮 */}
                            <button className={style['project-button']}
                                onClick={handleRefresh}
                                loading={loading}><UndoOutlined /></button>
                            <Button color="cyan" variant="solid" onClick={showModal}>+新增</Button>
                        </div>
                        {/* 新增函件模态框 */}
                        <Modal
                            title="新建确认函件"
                            open={isModalOpen}
                            onOk={handleOk}
                            onCancel={handleCancel}
                            okText="确认发署"
                            cancelText="取消"
                            confirmLoading={uploading}
                        >
                            {/* 确认类型选择 */}
                            <p>确认类型:</p>
                            <Radio.Group onChange={onChangeRadio} value={selectedValue}>
                                <Radio value="9">阶段确认</Radio>
                                <Radio value="6">需求确认</Radio>
                            </Radio.Group>
                            {/* 任务阶段选择 */}
                            <p>选择任务阶段:</p>
                            <select
                                value={selectedPhase}
                                onChange={(e) => setSelectedPhase(e.target.value)}
                                className={style['project-select']}
                            >
                                <option value="">请选择</option>
                                <option value="产品阶段">产品阶段</option>
                                <option value="设计阶段">设计阶段</option>
                                <option value="交付阶段">交付阶段</option>
                                <option value="需求变更">需求变更</option>
                            </select>

                            {/* 文件上传区域 */}
                            <p>上传签字文件:</p>
                            <div>
                                {/* PDF文件上传 */}
                                <div className={style['project-body-down']}>
                                    <span className={style['project-body-down-span']}>*</span>
                                    <label className={style['project-body-down-label']}>上传签字文件：</label>
                                    <div className={style['project-body-down-div']}>
                                        <input type="file" accept=".pdf" onChange={(e) => {
                                            if (e.target.files && e.target.files[0]) {
                                                const file = e.target.files[0];
                                                if (file.type !== 'application/pdf') {
                                                    message.error('请选择PDF文件');
                                                    return;
                                                }
                                                if (file.size > 10 * 1024 * 1024) {
                                                    message.error('文件大小不能超过10MB');
                                                    return;
                                                }
                                                setPdfFile(file);
                                            }
                                        }} style={{ display: 'none' }} id="pdf-file" />
                                        <label htmlFor="pdf-file" className={style['project-body-down-div-label']}>+ 选择PDF文件</label>
                                        {pdfFile && <span style={{ marginLeft: '10px', color: 'green' }}>✓ {pdfFile.name}</span>}
                                    </div>
                                </div>
                                {/* Word文件上传 */}
                                <div className={style['project-body-down']}>
                                    <span className={style['project-body-down-span']}>*</span>
                                    <label className={style['project-body-down-label']}>上传原文件：</label>
                                    <div className={style['project-body-down-div']}>
                                        <input type="file" accept=".doc,.docx" onChange={(e) => {
                                            if (e.target.files && e.target.files[0]) {
                                                const file = e.target.files[0];
                                                if (!file.name.match(/\.(doc|docx)$/i)) {
                                                    message.error('请选择Word文件');
                                                    return;
                                                }
                                                if (file.size > 10 * 1024 * 1024) {
                                                    message.error('文件大小不能超过10MB');
                                                    return;
                                                }
                                                setWordFile(file);
                                            }
                                        }} style={{ display: 'none' }} id="word-file" />
                                        <label htmlFor="word-file" className={style['project-body-down-div-label']}>+ 选择word文件</label>
                                        {wordFile && <span style={{ marginLeft: '10px', color: 'green' }}>✓ {wordFile.name}</span>}
                                    </div>
                                </div>
                            </div>
                        </Modal>
                        {/* 预览模态框 */}
                        {previewData && (
                            <Modal
                                title="函件详情预览"
                                open={isPreviewModalOpen}
                                onCancel={handlePreviewCancel}
                                footer={[
                                    <Button key="close" onClick={handlePreviewCancel}>
                                        关闭
                                    </Button>
                                ]}
                            >
                                <div className={style['preview-content']}>
                                    <p><strong>ID:</strong> {previewData.ID}</p>
                                    <p><strong>确认类型:</strong> {previewData.type}</p>
                                    <p><strong>确认阶段:</strong> {previewData.phase}</p>
                                    <p><strong>客户对接人:</strong> {previewData.client}</p>
                                    <p><strong>联系电话:</strong> {previewData.phone}</p>
                                    <p><strong>签署状态:</strong> {previewData.status}</p>
                                    <p><strong>创建人:</strong> {previewData.creator}</p>
                                    <p><strong>创建时间:</strong> {previewData.createTime}</p>
                                    <p><strong>更新时间:</strong> {previewData.updateTime}</p>
                                    <p><strong>天数:</strong> {previewData.days || 0}天</p>
                                    <p><strong>签字文件:</strong> <a href="#" onClick={(e) => { e.preventDefault(); handleFileClick(previewData.signFile, 'pdf'); }}>{previewData.signFile}</a></p>
                                    <p><strong>原文件:</strong> <a href="#" onClick={(e) => { e.preventDefault(); handleFileClick(previewData.origFile, 'word'); }}>{previewData.origFile}</a></p>
                                </div>
                            </Modal>
                        )}
                        {/* 搜索区域 */}
                        <div>
                            <input
                                type="text"
                                placeholder="创建人"
                                className={style['project-search']}
                                value={searchCreator}
                                onChange={(e) => setSearchCreator(e.target.value)}
                            />
                            <input
                                type="text"
                                placeholder="联系电话"
                                className={style['project-search']}
                                value={searchPhone}
                                onChange={(e) => setSearchPhone(e.target.value)}
                            />
                            <button className={style['project-button']} onClick={handleSearch}><SearchOutlined /></button>
                            <button 
                                className={style['project-button'] + (viewMode === 'list' ? ' ' + style['active'] : '')}
                                onClick={() => handleViewModeChange('list')}
                            >
                                <UnorderedListOutlined />
                            </button>
                            <button 
                                className={style['project-button'] + (viewMode === 'card' ? ' ' + style['active'] : '')}
                                onClick={() => handleViewModeChange('card')}
                            >
                                <AppstoreOutlined />
                            </button>
                            <button className={style['project-button']} onClick={handleExportExcel}><LineHeightOutlined /></button>
                        </div>
                    </div>
                    {/* 表格区域 */}
                    {viewMode === 'list' ? (
                        <div style={{ overflowX: 'auto', marginTop: 24 }}>
                            <table className={style['p-table']}>
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>确认类型</th>
                                        <th>确认阶段</th>
                                        <th>签字文件</th>
                                        <th>原文件</th>
                                        <th>客户对接人</th>
                                        <th>联系电话</th>
                                        <th>签署状态</th>
                                        <th>创建人</th>
                                        <th>创建时间</th>
                                        <th>更新时间</th>
                                        <th>天数</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {/* 遍历表格数据 */}
                                    {tableData.map(row => (
                                        <tr key={row._id}>
                                            <td>{row.ID}</td>
                                            <td>{row.type}</td>
                                            <td>{row.phase}</td>
                                            {/* 签字文件链接 */}
                                            <td>
                                                <a 
                                                    href="#" 
                                                    onClick={(e) => {
                                                        e.preventDefault();
                                                        handleFileClick(row.signFile, 'pdf');
                                                    }}
                                                >
                                                    {row.signFile}
                                                </a>
                                            </td>
                                            {/* 原文件链接 */}
                                            <td>
                                                <a 
                                                    href="#" 
                                                    onClick={(e) => {
                                                        e.preventDefault();
                                                        handleFileClick(row.origFile, 'word');
                                                    }}
                                                >
                                                    {row.origFile}
                                                </a>
                                            </td>
                                            <td>{row.client}</td>
                                            <td>{row.phone}</td>
                                            <td><span className={style['p-status'] + ' ' + style[`p-status-${row.statusType}`]}>{row.status}</span></td>
                                            <td>{row.creator}</td>
                                            <td>{row.createTime}</td>
                                            <td>{row.updateTime}</td>
                                            <td>{row.days || 0}天</td>
                                            {/* 操作按钮 */}
                                            <td>
                                                <button className={style['p-btn'] + ' ' + style['p-btn-blue']}>已签署</button>
                                                <button 
                                                    className={style['p-btn'] + ' ' + style['p-btn-orange']}
                                                    onClick={() => handlePreview(row)}
                                                >预览</button>
                                                <button
                                                    className={style['p-btn'] + ' ' + style['p-btn-green']}
                                                    onClick={() => handleDelete(row._id)}
                                                >删除</button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    ) : (
                        <div style={{ marginTop: 24 }}>
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '16px' }}>
                                {tableData.map(row => (
                                    <div key={row._id} style={{ 
                                        border: '1px solid #d9d9d9', 
                                        borderRadius: '8px', 
                                        padding: '16px',
                                        backgroundColor: '#fff',
                                        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                                    }}>
                                        <div style={{ marginBottom: '12px' }}>
                                            <strong>ID: {row.ID}</strong>
                                            <span style={{ 
                                                float: 'right', 
                                                padding: '2px 8px', 
                                                borderRadius: '4px',
                                                fontSize: '12px',
                                                backgroundColor: row.statusType === 'blue' ? '#e6f7ff' : 
                                                               row.statusType === 'orange' ? '#fff7e6' : '#f5f5f5',
                                                color: row.statusType === 'blue' ? '#1890ff' : 
                                                       row.statusType === 'orange' ? '#fa8c16' : '#666'
                                            }}>
                                                {row.status}
                                            </span>
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>确认类型:</strong> {row.type}
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>确认阶段:</strong> {row.phase}
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>客户对接人:</strong> {row.client}
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>联系电话:</strong> {row.phone}
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>创建人:</strong> {row.creator}
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>创建时间:</strong> {row.createTime}
                                        </div>
                                        <div style={{ marginBottom: '8px' }}>
                                            <strong>天数:</strong> {row.days || 0}天
                                        </div>
                                        <div style={{ marginBottom: '12px' }}>
                                            <strong>签字文件:</strong> 
                                            <a 
                                                href="#" 
                                                onClick={(e) => {
                                                    e.preventDefault();
                                                    handleFileClick(row.signFile, 'pdf');
                                                }}
                                                style={{ color: '#1890ff', marginLeft: '4px' }}
                                            >
                                                {row.signFile}
                                            </a>
                                        </div>
                                        <div style={{ marginBottom: '12px' }}>
                                            <strong>原文件:</strong> 
                                            <a 
                                                href="#" 
                                                onClick={(e) => {
                                                    e.preventDefault();
                                                    handleFileClick(row.origFile, 'word');
                                                }}
                                                style={{ color: '#1890ff', marginLeft: '4px' }}
                                            >
                                                {row.origFile}
                                            </a>
                                        </div>
                                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
                                            <button className={style['p-btn'] + ' ' + style['p-btn-blue']} style={{ fontSize: '12px', padding: '4px 8px' }}>已签署</button>
                                            <button 
                                                className={style['p-btn'] + ' ' + style['p-btn-orange']}
                                                onClick={() => handlePreview(row)}
                                                style={{ fontSize: '12px', padding: '4px 8px' }}
                                            >预览</button>
                                            <button
                                                className={style['p-btn'] + ' ' + style['p-btn-green']}
                                                onClick={() => handleDelete(row._id)}
                                                style={{ fontSize: '12px', padding: '4px 8px' }}
                                            >删除</button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                    {/* 分页组件 */}
                    <div className={style['pagination-container']}>
                        <Pagination
                            current={currentPage}
                            pageSize={pageSize}
                            total={total}
                            onChange={handlePageChange}
                            onShowSizeChange={handlePageSizeChange}
                            showSizeChanger
                            showQuickJumper
                            showTotal={(total) => `共 ${total} 条`}
                            pageSizeOptions={['2', '3', '5', '10']}
                        />
                    </div>
                </div>
            </div>
        </>
    );
};

export default ProjectFunctionList;